package edu.hcnu.service.impl;

import edu.hcnu.domain.Customer;
import edu.hcnu.domain.LoginUser;
import lombok.extern.slf4j.Slf4j;
import edu.hcnu.mapper.AuthorityMapper;
import edu.hcnu.mapper.CustomerAuthorityMapper;
import edu.hcnu.mapper.CustomerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: Administrator
 * @time: 2022/12/21 21:31
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private AuthorityMapper authorityMapper;

    @Autowired
    private CustomerAuthorityMapper customerAuthorityMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("登录用户名{}", username);

        //查询用户信息
        Customer customer = customerMapper.selectSysUserByUsername(username);

        log.info("数据库的登录信息 {}", customer);

        //如果没有查询到用户就抛出异常
        if (Objects.isNull(customer)) {
            log.info("用户错误");
            throw new RuntimeException("用户名或者密码错误");
        }

        // 查询用户所具有的权限信息
//        List<CommunityUserPerm> list = menuMapper.selectRidsByUserId(user.getId());
        List<Integer> integers = customerAuthorityMapper.selectAidsByUserId(customer.getId());

        List<String> collect = integers.stream().map((item) -> authorityMapper.queryCodeByAid(item)
        ).collect(Collectors.toList());


        //把数据封装成UserDetails返回
        return new LoginUser(customer, collect);
    }
}
